#!/usr/bin/python
# vim:fileencoding=utf8

if __name__ == '__main__':
    import os
    import sys
    mydir = os.path.dirname(__file__)
    sys.path.append(os.path.join(mydir, '..', '..'))


from xml.etree import ElementTree

from gnTai.aiexception import AIException
from gnTai.words.noun import Noun
from gnTai.words.verb import Verb
from gnTai.words import punctuation

class Dictionary:
    """
    Класс словарь, основная идея, по строке хранит список слов,
    которыми может быть эта строка в различных формах.
    """
    def __init__(self):
        self.dictionary = {}
        self.dictionary['.'] = [punctuation.Dot()]
        self.dictionary['!'] = [punctuation.Interrogation()]
        self.dictionary['?'] = [punctuation.Question()]
        self.dictionary[','] = [punctuation.Comma()]


    def __getitem__(self, string):
        try:
            return self.dictionary.__getitem__(string)
        except KeyError:
            raise AIException("Неизвестное слово '%s'." % string)
    
    def load(self, file_name):
        tree = ElementTree.parse(file_name)
        for word_element in tree.getroot():
            if word_element.tag != 'word':
                raise AIException(
                        'Неизвестный тэг %s в файле %s' % (word_element.tag, file_name)
                        )
            else:
                self.load_word(word_element)
    
    def load_word(self, word_element):
        for subnode in word_element:
            if subnode.tag == 'base':
                base = subnode.text
            else:
                try:
                    cls = eval(subnode.tag.capitalize())
                except:
                    raise AIException(
                            'Неизвестная часть речи.'
                            )
                word = cls(base)
                for form in word.uniq_forms():
                    self.dictionary.setdefault(form, []).append(word)

    @classmethod
    def load_from_file(cls, filename):
        d = Dictionary()
        d.load(filename)
        return d

if __name__ == '__main__':
    d = Dictionary()
    words_file = os.path.join(mydir, '..', '..', '..', 'data',  'words.xml')
    d.load(words_file)
    print d.dictionary
    print [", ".join(w.all_forms()) for w in d['apple']]
    print [w.get_type() for w in d['human']]
